import 'package:dio/dio.dart';
import 'secure_interceptor.dart';

class ApiClient {
  static const String baseUrl = 'http://localhost:8081'; // 根据实际情况修改
  
  late final Dio _dio;
  
  ApiClient() {
    _dio = Dio(BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: const Duration(seconds: 5),
      receiveTimeout: const Duration(seconds: 5),
      headers: {
        'Content-Type': 'application/json',
      },
    ));
    
    // 添加加密拦截器
    _dio.interceptors.add(SecureCommunicationInterceptor());
    
    // 添加日志拦截器
    _dio.interceptors.add(LogInterceptor(
      requestBody: true,
      responseBody: true,
      logPrint: (obj) => print(obj),
    ));
  }
  
  // 登录
  Future<Map<String, dynamic>> login(String username, String password) async {
    try {
      print('🔐 Attempting login with username: $username');
      final requestData = {
        'username': username,
        'password': password,
      };
      print('📤 Request data: $requestData');
      
      final response = await _dio.post('/api/login', data: requestData);
      print('📥 Response status: ${response.statusCode}');
      print('📥 Response data: ${response.data}');
      print('📥 Response data type: ${response.data.runtimeType}');
      
      // 检查响应是否包含错误信息
      if (response.data != null && response.data is Map<String, dynamic>) {
        final responseMap = response.data as Map<String, dynamic>;
        
        // 检查是否有处理错误
        if (responseMap.containsKey('error')) {
          throw Exception('API Error: ${responseMap['error']}');
        }
        
        print('✅ Login successful, returning response data');
        return responseMap;
      } else {
        print('⚠️ Invalid response format');
        throw Exception('Invalid response format');
      }
    } on DioException catch (e) {
      print('❌ Login DioException: ${e.toString()}');
      print('❌ Error type: ${e.type}');
      print('❌ Error message: ${e.message}');
      if (e.response != null) {
        print('❌ Response status: ${e.response?.statusCode}');
        print('❌ Response data: ${e.response?.data}');
      }
      throw _handleError(e);
    } catch (e) {
      print('❌ Login general error: $e');
      print('❌ Error type: ${e.runtimeType}');
      rethrow;
    }
  }
  
  // 获取用户信息
  Future<Map<String, dynamic>> getUserInfo() async {
    try {
      final response = await _dio.get('/api/user');
      return response.data;
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }
  
  // 更新用户信息
  Future<Map<String, dynamic>> updateUserInfo(Map<String, dynamic> userInfo) async {
    try {
      final response = await _dio.put('/api/user', data: userInfo);
      return response.data;
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }
  
  // 健康检查（不加密）
  Future<Map<String, dynamic>> ping() async {
    try {
      final response = await _dio.get('/ping');
      return response.data;
    } on DioException catch (e) {
      throw _handleError(e);
    }
  }
  
  String _handleError(DioException e) {
    switch (e.type) {
      case DioExceptionType.connectionTimeout:
        return 'Connection timeout';
      case DioExceptionType.sendTimeout:
        return 'Send timeout';
      case DioExceptionType.receiveTimeout:
        return 'Receive timeout';
      case DioExceptionType.badResponse:
        return 'Bad response: ${e.response?.statusCode}';
      case DioExceptionType.cancel:
        return 'Request cancelled';
      default:
        return 'Network error: ${e.message}';
    }
  }
}
